package com.keydom.ropeskipping;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.clj.fastble.BleManager;
import com.keydom.ropeskipping.dot.StudentHomeworkDTO;
import com.keydom.ropeskipping.utils.banner.BannerAdapter;
import com.keydom.ropeskipping.utils.banner.ColorUtil;
import com.keydom.ropeskipping.utils.banner.ScaleTransformer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FirstFragment extends Fragment {
    private String TAG = "FirstFragment";
    private ViewPager viewPager;
    private RelativeLayout viewPagerRootView;
    private TextView textType;
    private TextView textName;
    private LinearLayout nullLayout;
    private LinearLayout nowLayout;
    private RecyclerView recyclerView;

    private final List<StudentHomeworkDTO> studentHomeworkDTOS = new ArrayList<>();
    private final List<Boolean> bottomList = new ArrayList<>();
    private int oldPosition = 1;
    private BannerAdapter pagerAdapter;
    private BaseQuickAdapter<Boolean, BaseViewHolder> adapter;
    /**
     * viewPager是否初始化完成
     */
    private boolean isFirstLoad = false;

    public void setStudentHomeworkDTOS(final List<StudentHomeworkDTO> studentHomeworkDTOList) {
        if (studentHomeworkDTOList.size() > 0) {
            isFirstLoad = false;
            bottomList.clear();
            this.studentHomeworkDTOS.clear();
            studentHomeworkDTOList.get(0).setSelected(true);
            this.studentHomeworkDTOS.add(null);
            this.studentHomeworkDTOS.addAll(studentHomeworkDTOList);
            this.studentHomeworkDTOS.add(null);

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    nullLayout.setVisibility(View.GONE);

                    for (int i = 0; i < studentHomeworkDTOList.size(); i++) {
                        bottomList.add(i == 0);
                    }
                    adapter.setNewData(bottomList);
                    adapter.notifyDataSetChanged();

                    oldPosition = 1;
                    pagerAdapter.setRefresh(true);
                    pagerAdapter.notifyDataSetChanged();
                    pagerAdapter.setRefresh(false);
                    //默认第一张图 左右都有图
                    viewPager.setCurrentItem(oldPosition);
                    textName.setText(studentHomeworkDTOS.get(oldPosition).getHomeworkName());
                    if (studentHomeworkDTOS.get(oldPosition).getType() == 0) {
                        //计时计数
                        textType.setText("计时计数作业");
                        textType.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.icon_jishijishu), null, null, null);
                    } else if (studentHomeworkDTOS.get(oldPosition).getType() == 1) {
                        //计时
                        textType.setText("计时作业");
                        textType.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.icon_jishi), null, null, null);
                    } else {
                        //计数
                        textType.setText("计数作业");
                        textType.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.icon_jishu), null, null, null);
                    }
                }
            });
        } else {
            nullLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_first, container, false);
        viewPager = view.findViewById(R.id.viewPager);
        viewPagerRootView = view.findViewById(R.id.viewPagerRootView);
        textType = view.findViewById(R.id.text_type);
        textName = view.findViewById(R.id.text_name);
        nullLayout = view.findViewById(R.id.null_layout);
        nowLayout = view.findViewById(R.id.now_layout);
        recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = getAdapter();
        recyclerView.setAdapter(adapter);

        nowLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (BleManager.getInstance().getAllConnectedDevice() == null || BleManager.getInstance().getAllConnectedDevice().size() == 0) {
                    Intent intent = new Intent(getContext(), ScanBleActivity.class);
                    intent.putExtra("data", studentHomeworkDTOS.get(viewPager.getCurrentItem()));
                    startActivity(intent);
                    return;
                }
                Intent intent = new Intent(getContext(), WorkActivity.class);
                intent.putExtra("data", studentHomeworkDTOS.get(viewPager.getCurrentItem()));
                startActivity(intent);
            }
        });
        initBannerViewPager();
        return view;
    }


    private void initBannerViewPager() {
        //设置适配器
        pagerAdapter = new BannerAdapter(studentHomeworkDTOS);
        viewPager.setAdapter(pagerAdapter);
        //Pager之间的间距
        viewPager.setPageMargin(3);
        //预加载
        viewPager.setOffscreenPageLimit(5);
        //设置两边小 中间大 【切记配合 xml: android:clipChildren="false" 参数使用】
        //图书
        viewPager.setPageTransformer(true, new ScaleTransformer());

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    viewPager.setCurrentItem(1);
                    return;
                }
                if (position == studentHomeworkDTOS.size() - 1) {
                    viewPager.setCurrentItem(studentHomeworkDTOS.size() - 2);
                    return;
                }

                studentHomeworkDTOS.get(oldPosition).setSelected(false);
                studentHomeworkDTOS.get(position).setSelected(true);

                Map<Integer, Boolean> map = new HashMap<>();
                map.put(oldPosition, studentHomeworkDTOS.get(oldPosition).isSelected());
                map.put(position, studentHomeworkDTOS.get(position).isSelected());
                pagerAdapter.setSelected(map);
                List<Integer> mPositions = new ArrayList<>();
                mPositions.add(oldPosition);
                mPositions.add(position);
                pagerAdapter.setmPositions(mPositions);
                pagerAdapter.notifyDataSetChanged();

                bottomList.set(oldPosition - 1, false);
                bottomList.set(position - 1, true);
                adapter.notifyDataSetChanged();
                int lastPosition;
                if (oldPosition > position) {
                    // 右滑
                    lastPosition = Math.max(position - 2, 0);
                } else {
                    // 左滑
                    lastPosition = Math.min(position, bottomList.size() - 1);
                }
                if (isFirstLoad) {
                    recyclerView.scrollToPosition(lastPosition);
                }
                oldPosition = position;

                textName.setText(studentHomeworkDTOS.get(position).getHomeworkName());
                if (studentHomeworkDTOS.get(position).getType() == 0) {
                    //计时计数
                    textType.setText("计时计数作业");
                    textType.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.icon_jishijishu), null, null, null);
                } else if (studentHomeworkDTOS.get(position).getType() == 1) {
                    //计时
                    textType.setText("计时作业");
                    textType.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.icon_jishi), null, null, null);
                } else {
                    //计数
                    textType.setText("计数作业");
                    textType.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(getContext(), R.mipmap.icon_jishu), null, null, null);
                }
                isFirstLoad = true;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        //viewPager左右两边滑动无效的处理
        viewPagerRootView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return viewPager.onTouchEvent(motionEvent);
            }
        });

        pagerAdapter.setOnItemClickListener(new BannerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick() {
                if (BleManager.getInstance().getAllConnectedDevice() == null || BleManager.getInstance().getAllConnectedDevice().size() == 0) {
                    Intent intent = new Intent(getContext(), ScanBleActivity.class);
                    intent.putExtra("data", studentHomeworkDTOS.get(viewPager.getCurrentItem()));
                    startActivity(intent);
                    return;
                }
                Intent intent = new Intent(getContext(), WorkActivity.class);
                intent.putExtra("data", studentHomeworkDTOS.get(viewPager.getCurrentItem()));
                startActivity(intent);
            }
        });
    }

    private BaseQuickAdapter<Boolean, BaseViewHolder> getAdapter()  {
        BaseQuickAdapter<Boolean, BaseViewHolder> adapter = new BaseQuickAdapter<Boolean, BaseViewHolder>(R.layout.recycler_bottom_item){
            @Override
            protected void convert(@NonNull BaseViewHolder helper, Boolean item) {
                View view = helper.getView(R.id.view);
                if (item) {
                    view.setBackgroundResource(R.drawable.shape_white_selected);
                } else {
                    view.setBackgroundResource(R.drawable.shape_white_unselected);
                }
            }
        };
        return adapter;
    }
}
